#include <stdlib.h>
#include <stdio.h>
#include <nds.h>

// common headers
#include "common.h"

// local headers

#include "main.h"

#define _VERSION_INT MAKE_VERSION(0, 0, 1, STATE_BETA, 1)
char _VERSION_STR[VERSION_STR_MAX_LEN+1];

// libraries id (zero terminated array)
u32 ids[]={ ID_LIBRARY_SOUND, 0 };

int init() {
	std->sprintf(_VERSION_STR, VERSION_FORMAT, VERSION_ARGS(_VERSION_INT));	// make version str 0.0.1b1

	return 0;
}

u32 query(u32 query) {
	switch(query) {
	case QUERY_NAME:		// plugin name
		return (u32)"sound player";
	case QUERY_VERSION_INT:	// plugin integer version
		return (u32)_VERSION_INT;
	case QUERY_VERSION_STR:	// plugin string version
		return (u32)_VERSION_STR;
	case QUERY_AUTHOR:		// plugin author
		return (u32)"SunDEV";
	case QUERY_IDS:			// libraries id (zero terminated array)
		return (u32)ids;
	case QUERY_FILEEXT:		// file extensions directly handled by the plugin
		return (u32)NULL;
	default:
		return 0;
	}
}

sLibProc *libsnd=NULL;

int main(int argc, char *argv[]) {
    sLibResult libres;
    sSInterface *SI;

	char *fn=(argc==1)?argv[0]:"/test.ogg";
	FILE *fd=NULL;
	sSInfos infos;

	std->iprintf("\x1b[2JPlaying file : %s\n", fn);	// clear screen and print filename

	// get library instance
	libsnd=api->newLibInstance((libres=api->getLibraryByFileExt(fn, tSOUND)).lib);
	if(!libsnd || !(SI=(sSInterface *)libsnd->query(QUERY_FSTRUCT))) {
		std->iprintf("Can't open sound library !\n");
		return 1;
	}

	// open file
	fd=f->open(fn, "rb");
	if(!fd) return 1;

	// bind this library instance and the file
	if(SI->assign(fd, libres.extid)) {
		std->iprintf("Invalid file format\n");
		f->close(fd);
		return 1;
	}

	// get infos on the music
	std->bzero(&infos, sizeof(sSInfos));
	if(!SI->getInfos(&infos))
		std->iprintf("File infos :\nchannels=%d\nsampling rate=%dHz\nduration=%d(%dms)\n",
			infos.channels,
			infos.samplingrate,
			infos.duration,
			SI->position2ms(infos.duration)
		);

	// play the sound
	if(SI->play()) {
		std->iprintf("Can't play the sound\n");
		SI->deassign();
		f->close(fd);
		return 1;
	}

	// control loop
	std->iprintf("\nPress A to pause/start\nPress B to stop\n");
	while(1) {
		if(nds->keysDown() & KEY_A) SI->pause();

		if(nds->keysDown() & KEY_B) {
			SI->stop();
			break;
		}

		nds->swiWaitForVBlank();
		nds->scanKeys();
	}

	// unbind the library and the file
	SI->deassign();

	// close file
	f->close(fd);

	return 0;
}

void deinit() {
	// delete library instance
	if(libsnd) api->deleteLibInstance(libsnd);
}

